# -*- coding:UTF-8 -*-
import time

from RPi import GPIO


class UltrasonicAvoid:
    def __init__(self, EchoPin, TrigPin):
        GPIO.setup(EchoPin, GPIO.IN)
        GPIO.setup(TrigPin, GPIO.OUT)

        self.EchoPin = EchoPin
        self.TrigPin = TrigPin

    def getDistance(self):
        GPIO.output(self.TrigPin, GPIO.HIGH)
        time.sleep(0.000015)
        GPIO.output(self.TrigPin, GPIO.LOW)
        while not GPIO.input(self.EchoPin):
            pass
            t1 = time.time()
        while GPIO.input(self.EchoPin):
            pass
            t2 = time.time()
        distance = ((t2 - t1) * 340 / 2) * 100
        time.sleep(0.01)
        return distance


class InfraredAvoid:
    def __init__(self, AvoidSensorLeft, AvoidSensorRight):
        GPIO.setup(AvoidSensorLeft, GPIO.IN)
        GPIO.setup(AvoidSensorRight, GPIO.IN)

        self.AvoidSensorLeft = AvoidSensorLeft
        self.AvoidSensorRight = AvoidSensorRight
        self.infrared_avoid_value = ''

    def getDistance(self):
        """
        避障红外引脚测试
        遇到障碍物,红外避障模块的指示灯亮,端口电平为LOW
        未遇到障碍物,红外避障模块的指示灯灭,端口电平为HIGH
        :return:
        """
        LeftSensorValue = GPIO.input(self.AvoidSensorLeft)
        RightSensorValue = GPIO.input(self.AvoidSensorRight)
        infrared_avoid_value_list = ['0', '0']
        infrared_avoid_value_list[0] = str(1 ^ LeftSensorValue)
        infrared_avoid_value_list[1] = str(1 ^ RightSensorValue)
        self.infrared_avoid_value = ''.join(infrared_avoid_value_list)
